//
//  StatusPictureView.swift
//  Tanenbaum_blog
//
//  Created by Tanenbaum on 15/8/2.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit
import SDWebImage

let StatusPictureCellID = "StatusPictureCellID"
let ZuoJStatusPictureViewSelectedNotification = "ZuoJStatusPictureViewSelectedNotification"
let ZuoJStatusPictureViewSelectedIndexKey = "ZuoJStatusPictureViewSelectedIndexKey"
let ZuoJStatusPictureViewSelectedURLsKey = "ZuoJStatusPictureViewSelectedURLsKey"

class StatusPictureView: UICollectionView {
    
    var status: Status? {
        didSet {
            
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return calcViewSize()
    }
    
    //计算视图的大小
    private func calcViewSize() ->CGSize {
        
        //准备基本变量
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        let rowCount = 3
       
        picturelayout.itemSize = itemSize
        
        let count = status?.pictureURLs?.count ?? 0
        
        //没有图片
        if count == 0 {
            
            return CGSizeZero
        }
        
        //一张图片
        if count == 1 {
            
            let key = status!.pictureURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            var size = CGSize(width: 150 , height: 120)
            if image != nil {
                
                size = image.size
            }
            size.width = itemSize.width < 40 ? 40 : size.width
            size.width = itemSize.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
            picturelayout.itemSize = size
            
            return size
        }
        
        // 4张图片
        if count == 4 {
            
            let w = itemSize.width * 2 + margin
            
            return CGSize(width: w, height: w)
        }
        
        //图片数量为 2.3.5.6.7.8.9.的时候
        let row = (count - 1)/rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(row) + margin * CGFloat(row-1)
        return CGSize(width: w, height: h)
    }
    
    private let picturelayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: picturelayout)
        backgroundColor = UIColor.whiteColor()
        
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellID)
        self.dataSource = self
        self.delegate = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// 在 swift 中，协议同样可以通过 extension 来写
extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        NSNotificationCenter.defaultCenter().postNotificationName(ZuoJStatusPictureViewSelectedNotification, object: self, userInfo: [ZuoJStatusPictureViewSelectedIndexKey:indexPath,ZuoJStatusPictureViewSelectedURLsKey:status!.largepictureURLs!])

        
    }
    func cellScreenRect(indexPath:NSIndexPath) -> CGRect {
        
        let cell = cellForItemAtIndexPath(indexPath)!
        
        return convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    func cellFullScreenRect(indexPath:NSIndexPath) ->CGRect {
        
         let key = status!.pictureURLs![indexPath.item].absoluteString
         let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
         let scale = image.size.height / image.size.width
         let screenSize = UIScreen.mainScreen().bounds.size
         let height = screenSize.width * scale
        
        var y: CGFloat = 0
        if height < screenSize.height {
            y = (screenSize.height - height)  * 0.5
        }
        return CGRect(x: 0, y: y, width: screenSize.width, height: height)
    }
    func  collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return status?.pictureURLs?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(StatusPictureCellID, forIndexPath: indexPath)as! StatusPictureViewCell
        
        cell.imageURL = status!.pictureURLs![indexPath.item]
        
        return cell
    }
    
    
}
class StatusPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        
        didSet {
            
            iconView.sd_setImageWithURL(imageURL!)
            
            gifView.hidden = ((imageURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareUI() {
        
        contentView.addSubview(iconView)
        iconView.addSubview(gifView)
        iconView.ff_Fill(contentView)
        gifView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
        
    }
    //MARK 懒加载
    private lazy var iconView: UIImageView = {
        
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
        
        }()
    
    private lazy var gifView: UIImageView = {
       
        let iv = UIImageView(image: UIImage(named: "timeline_image_gif"))
        return iv
        
    }()
}


